package com.xm.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class FileUtil {
    public static void main(String[] args) throws IOException {
        System.out.println(getResourcePath("encrypt/license.txt"));
        System.out.println(getResourcePath2("config.properties"));
        System.out.println(getResourcePath2("encrypt/license.txt"));

        System.out.println(readConfMap());
    }

    private static final ResourceLoader resourceLoader = new DefaultResourceLoader();
    private static final Map<String, Object> confMap = new HashMap<>();

    //私有化构造方法
    private FileUtil() {
    }

    /**
     * 获取根目录下资源文件绝对路径
     * @param path 根目录下资源文件相对路径（path from source root）
     * @return 返回绝对路径
     */
    public static String getResourcePath(String path) {
        URL resourceUrl = FileUtil.class.getResource("/" + path);
        if (resourceUrl == null) {
            return null;
        }
        return resourceUrl.getPath();
    }

    public static String getResourcePathUtf8(String path) throws UnsupportedEncodingException {
        return URLDecoder.decode(Objects.requireNonNull(getResourcePath(path)), "UTF-8");
    }

    /**
     * 获取根目录下资源文件绝对路径
     * @param path 根目录下资源文件相对路径（path from source root）
     * @return 返回绝对路径
     */
    public static String getResourcePath2(String path) {
        Resource resource = resourceLoader.getResource("classpath:" + path);
        URL resourceUrl = null;
        try {
            resourceUrl = resource.getURL();
        } catch (IOException e) {
            log.error("系统异常", e);
        }
        if (resourceUrl == null) {
            return null;
        }
        return resourceUrl.getPath();
    }

    /**
     * 获取资源文件config.properties所有配置项
     * @return 返回key-value所有配置项
     */
    public static Map<String, Object> readConfMap(){
        if(confMap.isEmpty()){
            ClassLoader classLoader = FileUtil.class.getClassLoader();
            InputStream resourceStream = classLoader.getResourceAsStream("config.properties");
            if (resourceStream!= null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream))) {
                    String line;
                    String[] lineArr;
                    while ((line = reader.readLine())!= null) {
                        lineArr = line.split("=");
                        confMap.put(lineArr[0], lineArr[1]);
                    }
                } catch (IOException e) {
                    log.error("系统异常", e);
                }
            }
        }

        return confMap;
    }

}
